﻿using NServiceBus;
using System;
using Microsoft.AspNetCore.Hosting;
using System.Linq;
using System.Threading.Tasks;
using DHJ.Cost.Configuration;

namespace DHJ.Cost.Web.Startup
{
    public class NServiceBusService
    {
        public IEndpointInstance Instance { get; set; }

        public NServiceBusService(IHostingEnvironment env)
        {
            var appConfiguration = env.GetAppConfiguration();

            var endpointName = appConfiguration["NServicebus:EndpointName"];
            var connectionString = appConfiguration["NServicebus:RabbitMqConnectionString"];

            var endpointConfiguration = new EndpointConfiguration(endpointName);
            var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();

            transport.UseConventionalRoutingTopology();

            transport.ConnectionString(connectionString);
            endpointConfiguration.SendFailedMessagesTo(endpointName + "_error");
            endpointConfiguration.EnableInstallers();

            Instance = Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult();
        }
    }
}
